import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Button, Col, Row, Spin, message } from 'antd';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { UserManageContext } from '../hooks';
import { DoubleRightOutlined, DoubleLeftOutlined } from '@ant-design/icons';
import { loopArray, onCloseModalCommon, onMouseOutBtn } from '@/utils';
import { OpenRoleLeftTreeModal } from './OpenRoleLeftTreeModal';
import { getUserByIDService, grantUserRoleService, userTreeOfRoleService } from '../services';
import { OpenRoleRightRowsModal } from './OpenRoleRightRowsModal';

interface IOpenRoleModalAPI {
  onClose: () => void;
  checkRowInfo: Record<string, any>;
  openModal: boolean;
}

export const OpenRoleModal: React.FC<IOpenRoleModalAPI> = ({ onClose, checkRowInfo, openModal }) => {
  /** 弹框Ref */
  const roleModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { userFixCls, rightRoladTabieUser } = useContext(UserManageContext);

  /** 保存选中角色树数据 */
  const [checkRoleRowsInfo, setCheckRoleRowsInfo] = useState<Record<string, any> | any>({
    roleCheckKeys: [],
    roleCheckRows: [],
  });

  /** 引入详情接口 */
  const { getUserByIDLoading, getUserByIDRun, getUserByIDInfo } = getUserByIDService();

  /** 获取角色树回调 */
  const roleCallback = (res: any) => {
    if (res && res?.msgFlag) {
      getUserByIDRun({
        userID: checkRowInfo?.id,
      });
    } else {
      message.error(res?.msg);
    }
  };
  /** 获取角色树 */
  const { userTreeOfRoleRun, userTreeOfRoleLoading, userTreeOfRoleData } = userTreeOfRoleService(roleCallback);

  /** 平铺角色树数据 */
  const loopRoleTreeList = useMemo(() => {
    return loopArray(userTreeOfRoleData);
  }, [userTreeOfRoleData?.length]);

  /** 初始化获取角色树 */
  useEffect(() => {
    if (openModal) {
      userTreeOfRoleRun();
    }
  }, [openModal]);

  /** 监听数据初始化 */
  useEffect(() => {
    if (userTreeOfRoleData?.length > 0 && getUserByIDInfo?.roleIds) {
      const roleIdList: string[] = getUserByIDInfo?.roleIds?.split(',');
      const checkRoleRows: Record<string, any>[] = loopRoleTreeList?.filter((item: any) => roleIdList?.includes(item?.id));
      setCheckRoleRowsInfo({
        roleCheckKeys: roleIdList,
        roleCheckRows: checkRoleRows,
      });
    }
  }, [userTreeOfRoleData, getUserByIDInfo]);

  /** 判断全选和反选 */
  const isAllCheck = () => {
    return checkRoleRowsInfo?.roleCheckKeys?.length >= loopRoleTreeList?.length ? true : false;
  };

  /** 全选/反选 */
  const allCheckSelect = (isCheck: boolean) => {
    if (isCheck) {
      setCheckRoleRowsInfo({
        roleCheckKeys: loopRoleTreeList?.map((item: any) => item?.id),
        roleCheckRows: loopRoleTreeList,
      });
    } else {
      setCheckRoleRowsInfo({
        roleCheckKeys: [],
        roleCheckRows: [],
      });
    }
  };

  /** 设置角色回调 */
  const grantCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message?.success(res?.msg);
      rightRoladTabieUser();
      onCloseModalCommon(roleModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入设置用户角色数据 */
  const { grantUserRoleLoading, grantUserRoleRun } = grantUserRoleService(grantCallback);

  /** 点击保存 */
  const onSave = () => {
    if (checkRoleRowsInfo?.roleCheckKeys?.length > 0) {
      const roleParams: Record<string, any> = {
        roleIds: checkRoleRowsInfo?.roleCheckKeys?.toString(),
        userIds: checkRowInfo?.id,
        versionNum: checkRowInfo?.versionNum,
      };
      grantUserRoleRun(roleParams);
    } else {
      message.warning('请至少选择一个角色！！！');
    }
  };
  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={roleModalRef}
      title={'授权角色'}
      width={document.body.clientWidth * 0.5}
      onCancel={onClose}
      bodyStyle={{ padding: '5px 10px' }}
      onOk={onSave}
      confirmLoading={userTreeOfRoleLoading || getUserByIDLoading || grantUserRoleLoading}
    >
      <Spin spinning={userTreeOfRoleLoading || getUserByIDLoading || grantUserRoleLoading}>
        <Row className={userFixCls + 'userSecopeCard'}>
          <OpenRoleLeftTreeModal roleInfoList={userTreeOfRoleData} setCheckRoleRowsInfo={setCheckRoleRowsInfo} checkRoleRowsInfo={checkRoleRowsInfo} />
          <Col
            span={2}
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              height: document.body.clientHeight * 0.4,
            }}
          >
            <Button
              style={{ marginBottom: 10 }}
              type={isAllCheck() ? 'dashed' : 'primary'}
              onClick={() => {
                allCheckSelect(true);
              }}
              onMouseOut={onMouseOutBtn}
            >
              <DoubleRightOutlined />
            </Button>
            <Button
              type={isAllCheck() ? 'primary' : 'dashed'}
              onClick={() => {
                allCheckSelect(false);
              }}
              onMouseOut={onMouseOutBtn}
            >
              <DoubleLeftOutlined />
            </Button>
          </Col>

          <OpenRoleRightRowsModal loopRoleTreeList={loopRoleTreeList} setCheckRoleRowsInfo={setCheckRoleRowsInfo} checkRoleRowsInfo={checkRoleRowsInfo} />
        </Row>
      </Spin>
    </OneModal>
  );
};
